var ctx = "http://localhost:8080/";
console.log(location.href);
$('#current_url').html(location.href);
//form序列化为json
$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
// 取得当前登录用户信息
function getCurrentPerson() {
    window.open('/hello/getCurrentPerson');
}
// 登录
function loginPerson() {
    let data = {
        username: $('#username').val(),
        password: $('#password').val()
    };
    $.ajax({
        type: 'post',
        url: '/hello/loginPerson',
        data: JSON.stringify(data),
        contentType: "application/json;charset=utf-8",
        success: function (data) {
            //alert(JSON.stringify(data));
            if (data.success) {
                alert(data.message);
                $('#logout').show();
                //推荐采用引用方式 ` " ' ' " `，【``】常用于引用一些结果
                $('#currentUsername').html(`欢迎，${data.vo.username}`);
                //把当前登录用户的信息存放到浏览器自带的session中
                sessionStorage['currentPerson'] = JSON.stringify(data.vo);
                /*
                //不推荐采用字符串拼接
                let text = '欢迎光临：' + data.vo.username + '!!!';
                $('#currentUsername').html(text);
                */
            } else {
                alert(data.message);
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            var msg = xhr.responseText;
            var response = JSON.parse(msg);
            alert('操作执行异常，请查看浏览器控制台信息');
            console.log(xhr);
            console.log(textStatus);
            console.log(errorThrown);
        }
    });
}

//获取url后的参数值
function getUrlParam(key) {
    var href = window.location.href;
    //alert(href);
    var url = href.split("?");
    if (url.length <= 1) {
        return "";
    }
    var params = url[1].split("&");
    for (var i = 0; i < params.length; i++) {
        var param = params[i].split("=");
        if (key == param[0]) {
            return param[1];
        }
    }
}

function getNowTime() {
    var nowtime = new Date();
    var year = nowtime.getFullYear();
    var month = nowtime.getMonth() + 1;
    var date = nowtime.getDate();
    return year + "年" + month + "月" + date + "日" + nowtime.toLocaleTimeString();
}


function IsPC() {
    var userAgentInfo = navigator.userAgent;
    var Agents = ["Android", "iPhone",
        "SymbianOS", "Windows Phone",
        "iPad", "iPod"];
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
}

function arrayRemove(arr, value) {
    return arr.filter(function (ele) {
        return ele != value;
    });
}

var W = window.parent.document;

/*
 * 取得当前的浏览器地址起始，比如http://localhost:8080/
 */
function getDomain() {
    var pro = window.location.protocol;
    var host = window.location.host;
    var domain = pro + "//" + host;
    return domain;
}


function reload() {
    var v = location.href;
    if (v.indexOf('?') < 0)
        v += '?_=' + Math.random();
    else
        v += '&_' + '=' + Math.random();
    location.href = v;
    //location.reload();
}

function addUrlParam(url, name, value) {
    url += '&';
    url += encodeURIComponent(name) + '=' + encodeURIComponent(value);
    return url;
}


// 加载图片编码等在前端
function loadImg(button_id, file_name_id, file_data_id, img_src_id, href_id) {
    //获取文件
    var file = $("#" + button_id)[0].files[0];
    if (!/image\/\w+/.test(file.type)) {
        alert("只能选择图片");
        return false;
    }
    $('#' + file_name_id).val(file.name);
    //$('#' + contentType_id).val(file.type);
    //创建读取文件的对象
    var reader = new FileReader();
    //创建文件读取相关的变量
    var base64Data;
    //为文件读取成功设置事件
    reader.onload = function (e) {
        base64Data = e.target.result;
        // data:image/jpeg;base64,打头的
        $('#' + file_data_id).val(base64Data.substring(base64Data.indexOf(",")));
        $('#' + img_src_id).attr('src', base64Data);
        //$('#' + href_id).attr('href', base64Data);
        $('#' + href_id).removeAttr('href');
    };
    //正式读取文件
    reader.readAsDataURL(file);
}

function loadFile(button_id, file_name_id, file_data_id, file_href_lable_id, href_id) {
    //获取文件
    var file = $("#" + button_id)[0].files[0];
    $('#' + file_name_id).val(file.name);
    //$('#' + contentType_id).val(file.type);
    //创建读取文件的对象
    var reader = new FileReader();
    //创建文件读取相关的变量
    var base64Data;
    //为文件读取成功设置事件
    reader.onload = function (e) {
        base64Data = e.target.result;
        $('#' + file_data_id).val(base64Data.substring(base64Data.indexOf(",")));
        $('#' + file_href_lable_id).html(file.name);
        //$('#' + href_id).attr('href', base64Data.substring(base64Data.indexOf(",")));
        $('#' + href_id).removeAttr('href');
    };
    //正式读取文件
    reader.readAsDataURL(file);
}

//打印
function printDiv(div) {
    var headstr = "<html><head><title></title></head><body>";
    var footstr = "</body>";
    var newstr = document.all.item(div).innerHTML;
    var oldstr = document.body.innerHTML;
    document.body.innerHTML = headstr + newstr + footstr;
    window.print();
    document.body.innerHTML = oldstr;
    return false;
}

function copyToClipboard(txt) {
    if (window.clipboardData) {

        window.clipboardData.clearData();

        clipboardData.setData("Text", txt);

        alert("复制成功！");

    } else if (navigator.userAgent.indexOf("Opera") != -1) {

        window.location = txt;

    } else if (window.netscape) {

        try {

            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");

        } catch (e) {

            alert("被浏览器拒绝！\n请在浏览器地址栏输入'about:config'并回车\n然后将 'signed.applets.codebase_principal_support'设置为'true'");

        }

        var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);

        if (!clip)

            return;

        var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);

        if (!trans)

            return;

        trans.addDataFlavor("text/unicode");

        var str = {};

        var len = {};

        var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);

        var copytext = txt;

        str.data = copytext;

        trans.setTransferData("text/unicode", str, copytext.length * 2);

        var clipid = Components.interfaces.nsIClipboard;

        if (!clip)

            return false;

        clip.setData(trans, null, clipid.kGlobalClipboard);

        alert("复制成功！");

    }
}